package cn.edu.ecut.threads;

import java.time.LocalDateTime;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadTest6 {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		
		// 创建线程池 ( 可以将线程池理解为保存了众多Thread实例的"集合" )
		ExecutorService es = Executors.newFixedThreadPool( 3 );
		
		// 通过实现Runnable接口来实现线程要完成的任务
		Runnable task1 = new Runnable() {
			@Override
			public void run() {
				for( int i = 1 ; i < 6 ; i++ ) {
					System.out.println( Thread.currentThread() + " : " + i );
				}
			}
		};
		
		// 向线程池提交任务
		es.submit( task1 );
		
		// 通过实现Callable接口来完成线程任务
		Callable<LocalDateTime> task2 = new Callable<LocalDateTime>() {
			@Override
			public LocalDateTime call() throws Exception {
				for( int i = 1 ; i < 6 ; i++ ) {
					System.out.println( Thread.currentThread() + " : " + i );
				}
				return LocalDateTime.now() ;
			}
		} ;
		
		// 向线程池提交任务 ( 并返回可以获取任务执行后所返回结果的Future对象 )
		Future<LocalDateTime> future = es.submit( task2 );
		
		// 从 Future 实例中获取 线程任务 所返回的结果
		LocalDateTime datetime = future.get();
		System.out.println( datetime );

		// 关闭线程池
		es.shutdown();
	}

}
